/*
 * @Author: jipeng.Li
 * @Date: 2020-01-14  15:32:52.91
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-03-03 14:47:58
 * @Description: 项目主页
 */

import React, { Component } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  SafeAreaView,
  StyleSheet,
  NativeModules
} from 'react-native';
import OrderInfoCard from '../components/order-info-card';
import HeadTabs from '../../../../../components/HeadTabs';
import XmList from '../../../../../components/XmList';
import {
  px2dp,
  mainBgColorLightGray,
  fontColorDeepRed,
  fontColorCoffee,
  fontColorSecDeepGray,
  mainBgColorWhite,
  fontColorBlack,
  fontColorLightGreen
} from '../../../../../common/styles';
import { msg } from '../../../../../common';
import OrderStatus from '../../../components/order_status';
import supply from '../../../../../api/supply';

export default class WaybillList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      orderId: '',
      orderNo: '',
      orderDetails: null,
      tabIndex: -1,
      orderList: [],
      hasMorePage: true,
      isLoading: false,
      showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      unitList: [],
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { orderId, orderNo } = params;
    this.unitList();
    this.setState({ orderId, orderNo }, () => {
      this.orderDetail(orderId);
      this.loadData();
    });
  }

  tabType = [
    // 0 未接单 1 待装货 2 运输中 3 已送达 4 已完成 5 作废
    { tab: '全部', type: -1 },
    { tab: '待装货', type: 1 },
    { tab: '运输中', type: 2 },
    { tab: '已送达', type: 3 },
    { tab: '已完成', type: 4 },
  ];

  orderStatus = {
    // 0 未接单 1 待装货 2 运输中 3 已送达 4 已完成 5 作废
    0: {
      color: fontColorDeepRed,
      icon: require('../../../../../image/wl/icon_right_red.png'),
      text: '未接单'
    },
    1: {
      color: fontColorDeepRed,
      icon: require('../../../../../image/wl/icon_right_red.png'),
      text: '待装货'
    },
    2: {
      color: fontColorCoffee,
      icon: require('../../../../../image/wl/icon_right_origre.png'),
      text: '运输中'
    },
    3: {
      color: fontColorLightGreen,
      icon: require('../../../../../image/wl/icon_right_green.png'),
      text: '已送达'
    },
    4: {
      color: fontColorSecDeepGray,
      icon: require('../../../../../image/wl/icon_right_gray.png'),
      text: '已完成'
    },
    5: {
      color: fontColorSecDeepGray,
      icon: require('../../../../../image/wl/icon_right_gray.png'),
      text: '作废'
    },
  }

  render() {
    const { tabIndex, orderList, hasMorePage, showFoot, isLoading, orderDetails, unitList } = this.state;
    console.log('=====best=====》', orderList);
    return (
      <SafeAreaView style={{ flex: 1 }}>
        {orderDetails && (
          <OrderInfoCard
            unitList={unitList}
            item={orderDetails}
            isOperate={false}
            rightIconIsShow={false}
          />
        )}
        <View style={style.container}>
          <HeadTabs
            tabSources={this.tabType}
            changeStatus={(type) => this.changeWaybillStatus(type)}
            status={tabIndex}
          />
          <XmList
            sources={orderList}
            renderItem={this._renderItem}
            style={style.xmListContainer}
            isLoading={isLoading}
            onDropdownRefresh={() => this.loadData()}
            hasMorePage={hasMorePage}
            onPullUpMore={() => this.LoadMore()}
            singleKey={item => item.id}
            showFoot={showFoot}
          />
        </View>
      </SafeAreaView>
    );
  }

  _renderItem = ({ item }) => {
    const { carNo, driveName, loadGoodsTime, wayBillId, waybillStatus, waybillWeight, weightUnit } = item;
    return (
      <TouchableOpacity
        activeOpacity={0.8}
        onPress={() => {
          msg.emit('router: goToNext', {
            routeName: 'WaybillDetails',
            businessNo: item.businessNo,
            plat: 1
          });
        }}
        style={style.itemContainer}
      >
        <View>
          <Text
            style={{
              color: fontColorBlack,
              fontSize: px2dp(28),
              fontWeight: 'bold'
            }}
          >
            {`${waybillWeight}${this.formatUnit(weightUnit)}`}
          </Text>
          <Text
            style={{
              color: '#9D9A95',
              fontSize: px2dp(26),
              marginTop: px2dp(15)
            }}
          >
            {`${loadGoodsTime} 装货`}
          </Text>
        </View>
        {waybillStatus && (
          <OrderStatus
            textColor={this.orderStatus[waybillStatus].color}
            rightIcon={this.orderStatus[waybillStatus].icon}
            statusText={this.orderStatus[waybillStatus].text}
          />
        )}
      </TouchableOpacity>
    );
  };

  changeWaybillStatus = (status) => {
    this.setState({ tabIndex: status }, () => this.loadData());
  }

  loadData() {
    this.setState({
      isLoading: true,
      orderList: [],
    }, () => {
      this.wayBillList();
    });
  }

  LoadMore() {
    // this.setState({ showFoot: 1 })
  }

  orderDetail = () => {
    const { orderId } = this.state;
    supply.orderDetail(orderId).then(res => {
      if (res.success) {
        this.setState({ orderDetails: res.data });
      }
    });
  }

  formatUnit = (unit) => {
    const { unitList } = this.state;
    if (!unit || unitList.length === 0) {
      return '';
    }
    const unitName = unitList.filter(u => u.code === unit);
    if (unitName.length > 0) {
      return unitName[0].name;
    }
    return unit;
  }

  /**
   * 接口调用
   */
  wayBillList = () => {
    const { orderNo, tabIndex } = this.state;
    supply.wayBillList({
      orderNo: orderNo,
      status: tabIndex === -1 ? '' : tabIndex
    }).then(res => {
      if (res.success) {
        this.setState({ orderList: res.data, isLoading: false });
        res.data.length === 0 && this.setState({ showFoot: 0 });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  unitList = () => {
    supply.unitList().then(res => {
      if (res.success) {
        this.setState({ unitList: res.data });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }
}
const style = StyleSheet.create({
  container: {
    flex: 1
  },
  xmListContainer: {
    backgroundColor: mainBgColorLightGray,
    padding: px2dp(24),
  },
  itemContainer: {
    flexDirection: 'row',
    backgroundColor: mainBgColorWhite,
    justifyContent: 'space-between',
    padding: px2dp(24),
    borderRadius: px2dp(10),
    marginBottom: px2dp(24)
  },
});
